package com.document;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.UnsupportedEncodingException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFCellStyle;
import org.apache.poi.hssf.usermodel.HSSFFont;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.hssf.util.HSSFColor;
import org.apache.poi.hssf.util.Region;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.view.ContextMenu;
import android.view.ContextMenu.ContextMenuInfo;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.webkit.WebChromeClient;
import android.webkit.WebView;
import android.widget.TextView;
import android.widget.Toast;
//读取Excel文件类  使用webview容器 实现放大 多点触控 截屏 文件分享功能
public class ViewFileExcel extends Activity {
	private WebView view;	
	private TextView t;	//显示文件名
	private String filepath;
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		 final Activity activity = this;
		getWindow().requestFeature(Window.FEATURE_PROGRESS);  		         
        // 取消掉状态栏  完成窗体的全屏显示
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, 
                WindowManager.LayoutParams.FLAG_FULLSCREEN); 
		setContentView(R.layout.view);
		
		view = (WebView)findViewById(R.id.show);
		t=(TextView)findViewById(R.id.filename_1);
		view.setWebChromeClient(new WebChromeClient() {   
              
	            public void onProgressChanged(WebView view, int newProgress) {   
	                // 设置WebView加载进度条 
	                activity.setProgress(newProgress * 100);   
	            }   
	        });   		
		
		 final String path = GetPath.getpath()+File.separator;
		 Intent i=getIntent();
         Uri uri=(Uri)i.getData();
        filepath=uri.getPath(); 
         File f=new File(filepath);
         String fn=f.getName();
         t.setText(fn);
		
         try {
        	 //调用解析Excel方法  解析出excel文件放在webview上
			ParseExcel(filepath,path);
		} catch (IOException e) {
			
			e.printStackTrace();
		}
        
		 	//设置网页缩放
     	view.getSettings().setSupportZoom(true);
		view.getSettings().setBuiltInZoomControls(true);
		view.getSettings().setDefaultTextEncodingName("UTF-8");
		view.getSettings().setUseWideViewPort(true);

		//view.getSettings().setLoadWithOverviewMode(true);
		view.loadUrl("file:/"+GetPath.getpath()+File.separator+"dhfj59rkek5orkt.html");
	
	}
	//重写onCreateContextMenu，实现复制文字
		public void onCreateContextMenu(ContextMenu menu, View v,
				ContextMenuInfo menuInfo) {
			
			//实例化工具类
					WebViewCopy copy = new WebViewCopy(this, view);
				copy.onCreateContextMenu(menu, v, menuInfo,0,"复制"); 
				super.onCreateContextMenu(menu, v, menuInfo);
				}

	public static void ParseExcel(String ExcelPath,String HTMLSavePath) throws IOException {
		FileInputStream inp = new FileInputStream(ExcelPath);
		HSSFWorkbook workbook = new HSSFWorkbook(inp);
		HSSFSheet sheet = workbook.getSheetAt(0);
		HSSFRow row = sheet.getRow(0);
		
		int rows = sheet.getLastRowNum();
		int cols = row.getLastCellNum();
		int dstart = -1; // 明细内容起始行
		int dend = -1;  // 明细内容结束行
		for(int i=0;i<=rows;i++){
			boolean find = false;
			for(int j=0;j<cols&&!find;j++){
				row = sheet.getRow(i);
				HSSFCell cell = row.getCell((short) j);
				if(cell != null && cell.getCellType() == HSSFCell.CELL_TYPE_STRING && cell.getStringCellValue() != null && cell.getStringCellValue().startsWith("D{")){
					if(dstart == -1){
						dstart = i;
					}
					dend = i;
					find = true;
				}
			}
		}
				
		// 转换为html
		String html = ConvertToHtml(sheet,workbook);
		
		File _html = new File(HTMLSavePath+File.separator+"dhfj59rkek5orkt.html");
		FileOutputStream stream;
		OutputStreamWriter writer; 
		try { 
		      stream = new FileOutputStream(_html); 
		      writer = new OutputStreamWriter(stream,"UTF-8"); 
		      writer.write(html);
		      writer.flush();
		      writer.close();
		}catch(Exception e){
		}
		
	}	
	
	//取RGB颜色
	private static String getColor(short c){
		if(c<8||c>63){
			return "";
		}
		String color = ((HSSFColor)HSSFColor.getIndexHash().get(new Integer(c))).getHexString();
		String[] cs = color.split(":");
		color = "#";
		for(int j=0;j<cs.length;j++){
			if(cs[j].length()==1){
				color+=cs[j]+cs[j];
			}else if(cs[j].length()==4){
				color+=cs[j].substring(2);
			}else{
				color+=cs[j];
			}
		}
		return color;
	}
	
	//Excel Sheet转换为html
	private static String ConvertToHtml(HSSFSheet sheet, HSSFWorkbook workbook) throws UnsupportedEncodingException {
		int row = sheet.getLastRowNum();
		HSSFRow _row = sheet.getRow(0);
		int col = _row.getLastCellNum();
		String[][][] tdinfo = new String[row][col][2];
		Map style = new HashMap();
		// 合并单元格
		for(int i=0;i<sheet.getNumMergedRegions();i++){
			Region m = sheet.getMergedRegionAt(i);
			int rs = m.getRowFrom();
			int re = m.getRowTo();
			int cs = m.getColumnFrom();
			int ce = m.getColumnTo();
			tdinfo[rs][cs][0] = "";
			if(re > rs){
				tdinfo[rs][cs][0] += " rowspan='"+(re-rs+1)+"'";
			}
			if(ce>cs){
				tdinfo[rs][cs][0] += " colspan='"+(ce-cs+1)+"'";
			}
			for(int x=rs;x<=re;x++){
				for(int y=cs;y<=ce;y++){
					if(x!=rs || y!=cs){
						tdinfo[x][y] = null;
					}
				}
			}
		}
		float[] width = new float[col];
		int widthsum = 0;
		int max = 0;
		// 列宽
		for(int i=0;i<col;i++){
			width[i] = sheet.getColumnWidth((short) i);
			if(width[i]>=width[max]){
				max = i;
			}
			widthsum += width[i];
		}
		// 最宽的一列不指定宽度
		width[max] = 0;
		// 设置单元格内容
		for(int i=0;i<row;i++){
			_row = sheet.getRow(i);
			for(int j=0;j<col;j++){
				if(tdinfo[i][j] == null){
					continue;
				}
				HSSFCell cell = _row.getCell((short) j);
				if(cell != null){
					HSSFCellStyle s = cell.getCellStyle();
					if(tdinfo[i][j][0] == null){
						tdinfo[i][j][0] = "";
					}
					// 设置单元格的样式
					tdinfo[i][j][0] += " class='"+getCssByStyle(s,workbook,style)+"'";
					// 设置单元格的值
					if(cell.getCellType() == HSSFCell.CELL_TYPE_STRING){
						tdinfo[i][j][1] = cell.getStringCellValue();
					}else if(cell.getCellType() == HSSFCell.CELL_TYPE_NUMERIC){
						tdinfo[i][j][1] = cell.getNumericCellValue()+"";
					}
				}else{
					tdinfo[i][j] = null;
				}
			}
		}
				
		StringBuffer br = new StringBuffer();
		br.append("<html xmlns:o='urn:schemas-microsoft-com:office:office' xmlns:x='urn:schemas-microsoft-com:office:excel' xmlns='http://www.w3.org/TR/REC-html40'>");
		br.append("<head><meta http-equiv=Content-Type content='text/html; charset=utf-8'><meta name=ProgId content=Excel.Sheet>");
		br.append("<style>");
		Iterator it = style.values().iterator();
		while(it.hasNext()){
			String[] css = (String[])it.next();
			br.append(css[1]);
		}
		br.append("</style></head><body>");
		br.append("<table cellspacing='0' cellpadding='0' style='border-collapse:collapse;'>");
		// 设置单元格的宽度
		for(int i=0;i<col;i++){
			if(i != max){
				br.append("<col width='"+Math.rint(width[i]/widthsum*100)+"%'>");
			}else{
				br.append("<col>");
			}
		}
		for(int i=0;i<row;i++){
			br.append("<tr>");
			for(int j=0;j<col;j++){
				if(tdinfo[i][j] != null){
					if(tdinfo[i][j][0] == null){
						tdinfo[i][j][0] = "";
					}
					if(tdinfo[i][j][1]==null){
						tdinfo[i][j][1] = " ";
					}
					br.append("<td "+tdinfo[i][j][0]+">"+tdinfo[i][j][1]+"</td>");
				}
			}
			br.append("</tr>");
		}
		br.append("</table></body></html>");
		return br.toString();
	}
	
	
	private static String getCssByStyle(HSSFCellStyle s, HSSFWorkbook workbook,Map style) {
		if(style.containsKey(s)){
			String[] css = (String[])style.get(s);
			return css[0];
		}else{
			String[] css = new String[2];
			css[0] = "c"+style.size();
			StringBuffer cssinfo = new StringBuffer();
			// 文字对齐方式
			switch(s.getAlignment()){
				case HSSFCellStyle.ALIGN_CENTER:
					cssinfo.append("text-align:center;");break;
				case HSSFCellStyle.ALIGN_LEFT:
					cssinfo.append("text-align:left;");break;
				case HSSFCellStyle.ALIGN_RIGHT:
					cssinfo.append("text-align:right;");break;
			}
			// 背景色
			cssinfo.append("background-color:"+getColor(s.getFillForegroundColor())+";");
			 //设置边框
			cssinfo.append("border-top:"+s.getBorderTop()+"px solid #000000;");
			cssinfo.append("border-left:"+s.getBorderLeft()+"px solid #000000;");
			cssinfo.append("border-right:"+s.getBorderRight()+"px solid #000000;");
			cssinfo.append("border-bottom:"+s.getBorderBottom()+"px solid #000000;");
			// 设置字体
			HSSFFont font = workbook.getFontAt(s.getFontIndex());
			cssinfo.append("font-size:"+font.getFontHeightInPoints()+"pt;");
			if(HSSFFont.BOLDWEIGHT_BOLD == font.getBoldweight()){
				cssinfo.append("font-weight: bold;");
			}
			cssinfo.append("font-family: "+font.getFontName()+";");
			if(font.getItalic()){
				cssinfo.append("font-style: italic;");
			}
			String fontcolor = getColor(font.getColor());{
				if(fontcolor.trim().length() > 0){
					cssinfo.append("color: "+fontcolor+";");
				}
			}
			css[1] = "."+css[0]+"{"+cssinfo.toString()+"}";
			style.put(s, css);
			return css[0];
		}
	}
	//添加菜单 实现截屏功能
		 public boolean onCreateOptionsMenu(Menu menu)    
		    {    
		            
		        menu.add(0, 0, 0, "截屏");  
		        menu.add(0, 1, 0, "发送");  
		        	          
		        return super.onCreateOptionsMenu(menu);    
		    }    
		    
		    @Override    
		    public boolean onOptionsItemSelected(MenuItem item)    
		    {    
		        switch(item.getItemId())    
		        {    
		            case 0:   
		                {   
		                	SimpleDateFormat formatter=new SimpleDateFormat("MM月dd日 HH.mm.ss");       
		                	Date curDate=new Date(System.currentTimeMillis());//获取当前时间       
		                	String str=formatter.format(curDate);
		               	 ShotView.shot(this,"mnt/sdcard/DCIM/Excel截图"+str+".png");
		                  
		                 Toast.makeText(getApplicationContext(), "截屏成功,已保存在mnt/sdcard/DCIM/Excel截图"+str+".png", Toast.LENGTH_LONG).show();
	             
		                    break;    
		                }  
		        
            case 1:   
               {   
               	//调用系统分享功能
		    		 Intent intent = new Intent(Intent.ACTION_SEND);  
		                intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);  
		                intent.putExtra(Intent.EXTRA_STREAM, Uri.fromFile(new File(filepath)));   
		                intent.setType("*/*");   //分享文件  
		                startActivity(Intent.createChooser(intent,"分享"));
		    		break;
        
                      
               }     
		                
		        }
				return false;}

	
}
